package by.dvrudenko.avtobaza.webapp.page.route.panel;

import java.util.Iterator;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.OrderByBorder;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.request.resource.ContextRelativeResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.dvrudenko.avtobaza.datamodel.Driver;
import by.dvrudenko.avtobaza.datamodel.Route;
import by.dvrudenko.avtobaza.datamodel.Route_;
import by.dvrudenko.avtobaza.datamodel.UserOrder;
import by.dvrudenko.avtobaza.datamodel.enums.OrderStatus;
import by.dvrudenko.avtobaza.datamodel.enums.UserRole;
import by.dvrudenko.avtobaza.services.DriverService;
import by.dvrudenko.avtobaza.services.RouteService;
import by.dvrudenko.avtobaza.webapp.page.AbstractPanel;
import by.dvrudenko.avtobaza.webapp.page.car.panel.CarDetailsPanel;
import by.dvrudenko.avtobaza.webapp.page.car.panel.CarListPanel;
import by.dvrudenko.avtobaza.webapp.page.car.panel.MyPagingNavigator;
import by.dvrudenko.avtobaza.webapp.page.createRoute.CreateRoutePage;
import by.dvrudenko.avtobaza.webapp.page.order.OrderPage;
import by.dvrudenko.avtobaza.webapp.utils.security.SecuredLinkForAdmin;
import by.dvrudenko.avtobaza.webapp.utils.security.SecuredLinkForAdminAjax;

public class RouteListPanel extends AbstractPanel {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(RouteListPanel.class);

	@Inject
	private RouteService routeService;

	@Inject
	private DriverService driverService;
	
	public RouteListPanel(String id, Route route) {
		super(id);
		setOutputMarkupId(true);
		final WebMarkupContainer tableBody = new WebMarkupContainer("wrapper-body");
		
		final WebMarkupContainer tableList = new WebMarkupContainer("list");
		tableBody.add(tableList);
		add(tableBody);
		// заполняем таблицу по переданному маршруту
		tableList.add(new Label("userOrder.cargoBeginningCity.cityName", new Model<String>(route.getUserOrder().getCargoBeginningCity().getCityName())));				
		tableList.add(new Label("userOrder.cargoFinalCity.cityName",new Model<String>(route.getUserOrder().getCargoFinalCity().getCityName())));			
		tableList.add(new Label("driver.user.name" , new Model<String>(route.getDriver().getUser().getName())));				
		tableList.add(new Label("driver.lastName", new Model<String>(route.getDriver().getLastName())));			
		tableList.add(new Label("car.carType.brand", new Model<String>(route.getCar().getCarType().getBrand())));				
		tableList.add(new Label("car.carType.model", new Model<String>(route.getCar().getCarType().getModel())));
		tableList.add(new Label("car.carType.type", new Model<String>(route.getCar().getCarType().getType())));		
		tableList.add(new Label("car.carryingCapacity", new Model<Integer>(route.getCar().getCarryingCapacity())));	
		tableList.add(new Label("car.volumeCapacity", new Model<Integer>(route.getCar().getVolumeCapacity())));		
		tableList.add(new Label("userOrder.orderStatus", new ResourceModel(route.getUserOrder().getOrderStatus().name())));		
		
		addLink(tableList, route);
		
		add(new Label("paging"));
	}

	public RouteListPanel(String id) {
		super(id);
		setOutputMarkupId(true);
		RouteDataProvider routeDataProvider = new RouteDataProvider();

		final WebMarkupContainer tableBody = new WebMarkupContainer("wrapper-body");

		add(tableBody);

		DataView<Route> dataView = new DataView<Route>("list", routeDataProvider, 5) {
			@Override
			protected void populateItem(Item<Route> item) {
				final Route route = item.getModelObject();				
				// заполняем таблицу характеристик маршрута
				item.add(new Label("userOrder.cargoBeginningCity.cityName"));				
				item.add(new Label("userOrder.cargoFinalCity.cityName"));			
				item.add(new Label("driver.user.name"));				
				item.add(new Label("driver.lastName"));			
				item.add(new Label("car.carType.brand"));				
				item.add(new Label("car.carType.model"));
				item.add(new Label("car.carType.type"));	
				item.add(new Label("car.carryingCapacity"));	
				item.add(new Label("car.volumeCapacity"));				
				item.add(new Label("userOrder.orderStatus" , new ResourceModel(route.getUserOrder().getOrderStatus().name())));	
				addLink(item, route);
			}
		};

		tableBody.add(dataView);

		add(new MyPagingNavigator("paging", dataView));

//		add(new OrderByBorder<SingularAttribute<Route, ?>>("sortByLastName", Route_.lastName, routeDataProvider));
//		add(new OrderByBorder<SingularAttribute<Route, ?>>("sortByCity", Route_.birthday, routeDataProvider));

			
	}

	private class RouteDataProvider extends SortableDataProvider<Route, SingularAttribute<Route, ?>> {

		public RouteDataProvider() {
			super();
			setSort(Route_.car, SortOrder.ASCENDING);
		}

		@Override
		public Iterator<? extends Route> iterator(long first, long count) {

			SingularAttribute<Route, ?> sortParam = getSort().getProperty();
			SortOrder propertySortOrder = getSortState().getPropertySortOrder(sortParam);
			boolean ascending = SortOrder.ASCENDING.equals(propertySortOrder);
			if (user.getRole().equals(UserRole.DRIVER)){
				// определяем водителя для которого нужно показать маршрут
				Driver driver = driverService.getDriverByUserId(user.getId());
				return routeService.getAllRoute(sortParam, ascending, (int) first, (int) count , 
						driver.getId()).iterator();
			}
			return routeService.getAllRoute(sortParam, ascending, (int) first, (int) count , null).iterator();
		}

		@Override
		public long size() { // доработать не правильно выводится размер для админа
				return routeService.getCount(user.getId());
		}

		@Override
		public IModel<Route> model(Route route) {
			return new CompoundPropertyModel<Route>(route);
		}
	}
	
	private void addLink(final WebMarkupContainer container, final Route route) {	
		// ссылка для удаления
		final Link edit = new SecuredLinkForAdmin("edit") {
			@Override
			public void onClick() {
				LOGGER.info(user.getLogin() + " - user click edit Route");
				setResponsePage(new CreateRoutePage(route, route.getUserOrder()));
			}
		};
		container.add(edit);
		
		// ссылка для удаления
		final AjaxLink remove = new SecuredLinkForAdminAjax("remove") {
			@Override
			public void onClick(AjaxRequestTarget target) {
				routeService.delete(route);
				LOGGER.info(user.getLogin() +  " - user delete route from DB");
				info(new ResourceModel("p.home.createorder.routeDelete").getObject());
				target.addChildren(getPage(), FeedbackPanel.class);	
				target.add(RouteListPanel.this);
			}
			// если состояние маршрута не закончен (finish), то ссылку для удаления показывать не надо
			@Override
			protected void onConfigure() {
				super.onConfigure();
				if (!route.getUserOrder().getOrderStatus().equals(OrderStatus.finish)){
					setVisible(false);
				};
			}
			
		};
		container.add(remove);
		
		if (route.getUserOrder().getOrderStatus().equals(OrderStatus.finish)){
			edit.setVisible(false);
		}

	}

}
